package com.beifu.manager.shiro;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.beifu.manager.api.domain.logon.MobileUserInfo;
import com.beifu.manager.api.token.UserPassAuthenticationToken;
import com.beifu.manager.model.Module;
import com.beifu.manager.model.Tree;
import com.beifu.manager.model.UserInfo;
import com.beifu.manager.service.user.UserService;
import com.utils.Constants;
import com.utils.TreeUtils;

/**
 * 自定义shiro认证
 * 
 * @author huahao
 *
 */
public class MyShiroRealm extends AuthorizingRealm {

	private Logger Log = Logger.getLogger(MyShiroRealm.class);

	@Autowired
	private UserService userService;

	/**
	 * 赋权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		Log.debug("===>正在赋权");
		ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
		Integer userId = Integer.valueOf(activeUser.getUserId());

		// 获取菜单资源权限
		List<Module> resourceList = userService.getModuleList(userId,Constants.ROLE_TYPE.WEB_ROLE,Integer.valueOf(Constants.MODULE_PLATFORM.WEB_MODULE).intValue());
		List<String> resList = new ArrayList<String>();
		for(Module module : resourceList){
			resList.add(module.getModulePath());
		}
		
		List<String> roleList = activeUser.getRoles();

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(new HashSet<String>(roleList));
		info.setStringPermissions(new HashSet<String>(resList));

		// 以上完成了动态地对用户授权
		Log.debug("role ===> " + roleList);
		Log.debug("permission ===> " + resList);
		return info;
	}

	/**
	 * 身份认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		Log.debug("===> 开始校验用户名和密码");
		
		if(token instanceof UserPassAuthenticationToken){//移动端登录
			return mobileLogon(token);
		}else{//web端登陆
			return webLogon(token);
		}
		
	}
	
	private AuthenticationInfo mobileLogon(AuthenticationToken token){
		
		UserPassAuthenticationToken userToken = (UserPassAuthenticationToken) token;
		
		UserInfo userInfo = new UserInfo();
		userInfo = userService.login(userToken.getUsername(), String.valueOf(userToken.getPassword()));
		
		List<Module> moduleList = userService.getModuleList(userInfo.getId(),Constants.ROLE_TYPE.MOBILE_ROLE,Integer.valueOf(Constants.MODULE_PLATFORM.MODULE_MODULE).intValue());
		
		MobileUserInfo mobileUserInfo = new MobileUserInfo();
		
		mobileUserInfo.setUserId(userInfo.getId().toString());
		mobileUserInfo.setLoginName(userInfo.getLoginName());
		mobileUserInfo.setUserName(userInfo.getUserName());
		mobileUserInfo.setOrganizeId(null == userInfo.getOrganizeId()?"":userInfo.getOrganizeId().toString());
		mobileUserInfo.setModuleList(moduleList);
		if(null != userInfo.getOrganize()){
			mobileUserInfo.setOrganizeName(userInfo.getOrganize().getOrganizeName());
			if(userInfo.getOrganize().getOrganizeType() != null){
                mobileUserInfo.setOrganizeType(userInfo.getOrganize().getOrganizeType()+"");
                mobileUserInfo.setOrganizeTypeName(Constants.ORGANIZER_TYPE_enum.codeOf(userInfo.getOrganize().getOrganizeType()+"").getName());
            }
		}
		
		
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(mobileUserInfo,
				userInfo.getLoginPassword(), getName());

		info.setCredentialsSalt(ByteSource.Util.bytes(userInfo.getLoginName().getBytes()));
		return info;
	}
	
	private AuthenticationInfo webLogon(AuthenticationToken token){
		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		
		if (StringUtils.isEmpty(userToken.getUsername())) {
			return null;
		}
		
		UserInfo userInfo = new UserInfo();
		userInfo = userService.login(userToken.getUsername(), String.valueOf(userToken.getPassword()));
		
		ActiveUser activeUser = new ActiveUser();
		
		List<Module> moduleList = userService.getModuleList(userInfo.getId(),Constants.ROLE_TYPE.WEB_ROLE,Integer.valueOf(Constants.MODULE_PLATFORM.WEB_MODULE).intValue());
		List<Tree> menus = new ArrayList<Tree>();
		//递归处理ModuleList,——》 List<Tree>
		menus = TreeUtils.module2TreeList(moduleList);

		activeUser.setUserId(userInfo.getId().toString());
		activeUser.setLoginName(userInfo.getLoginName());
		activeUser.setUserName(userInfo.getUserName());
		activeUser.setOrganizeId(null == userInfo.getOrganizeId()?"":userInfo.getOrganizeId().toString());
		activeUser.setMenus(menus);
		
		if (null == userInfo.getRoleId()){
			activeUser.setRoles(null);
			Log.info("尚未为该用户分配权限！");
//			throw new AuthenticationException("禁止登录，尚未为该用户分配权限！");
		} else {
			String roleId = userInfo.getRoleId().toString();
			List<String> roles = new ArrayList<String>();
			roles.add(roleId);
			activeUser.setRoles(roles);
		}

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser,
				userInfo.getLoginPassword(), getName());

		info.setCredentialsSalt(ByteSource.Util.bytes(userInfo.getLoginName().getBytes()));
		return info;
	}
	
	
	@Override
	public String getName() {
		return "UserShiroRealm";
	}

}
